<template>
  <div class="position">
    <div class="container">
    <div class="title_color">{{t('Holdings')}}</div>
    <div class="label">
      <div
        class=""
        :class="[uType == 'normal'? 'active' : '']"
        @click="checkUType('normal')"
      >
        {{t('Holdings')}}
      </div>
      <div
        class=""
        :class="[uType == 'closing' ? 'active' : '']"
        @click="checkUType('closing')"
      >
        {{t('Closed positions')}}
      </div>
    </div>
    <template v-for="e in orderList" :key="e.id" v-if="orderList.length">
      <div class="cell" v-if="uType == 'normal'" @click="go(e)">
        <div class="cell-item-head" >
          <div>
            <div class="cell-item-head-title">{{e.name}}</div>
            <div class="cell-item-head-title-small">
              <span> {{e.ticker}}, </span><span> {{e.excode}} </span>
            </div>
          </div>
          <div class="cell-item-head-value" @click.stop="sell(e)">{{t('Sell')}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-name">{{t('order number')}}</div>
          <div class="cell-item-value">{{e.id}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-name">{{t('order time')}}</div>
          <div class="cell-item-value">{{date(new Date(e.order_time), 'ss:mm:hh DD/MM/YYYY')}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-rows-name">{{t('Service Fee')}}</div>
          <div class="cell-item-rows-value" style="color: rgb(2, 175, 116)">₹{{e.fee}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-rows-name">{{t('Buying Price')}}</div>
          <div class="cell-item-rows-value" style="color: rgb(2, 175, 116)">₹{{e.buy_price}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-rows-name cell-item-rows-name-padding">Current Price</div>
          <div class="cell-item-rows-value" style="color: rgb(2, 175, 116)">₹{{e.close}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-rows-name">{{t('Number of Shares Held')}}</div>
          <div class="cell-item-rows-value" style="color: rgb(2, 175, 116)">{{decimalpre(e.quantity)}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-rows-name cell-item-rows-name-padding">{{t('Position Amount')}}</div>
          <div class="cell-item-rows-value" :class="`${e.profit >= 0 ? 'upper' : 'lower'}`">₹{{decimalpre(e.postionAmount)}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-rows-name">{{t('Profit')}}</div>
          <div class="cell-item-rows-value" :class="`${e.profit >= 0 ? 'upper' : 'lower'}`">₹{{decimalpre(e.profit)}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-rows-name cell-item-rows-name-padding">{{t('Direction')}}</div>
          <div class="cell-item-rows-value" :class="`${e.profit >= 0 ? 'upper' : 'lower'}`">{{e.direc}}</div>
        </div>
      </div>

      <div class="cell" v-else @click="go(e)">
        <div class="cell-item-head">
          <div>
            <div class="cell-item-head-title">{{e.name}}.</div>
            <div class="cell-item-head-title-small">
              <span> {{e.ticker}}, </span><span> {{e.excode}} </span>
            </div>
          </div>
          <!---->
        </div>
        <div class="cell-item">
          <div class="cell-item-name">{{t('Closing Time')}}</div>
          <div class="cell-item-value">{{date(new Date(e.closing_time), 'ss:mm:hh DD/MM/YYYY')}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-name">{{t('order number')}}</div>
          <div class="cell-item-value">{{e.id}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-name">{{t('order time')}}</div>
          <div class="cell-item-value">{{date(new Date(e.order_time), 'ss:mm:hh DD/MM/YYYY')}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-rows-name">{{t('Service Fee')}}</div>
          <div class="cell-item-rows-value" style="color: rgb(2, 175, 116)">₹{{decimalpre(e.fee)}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-rows-name">{{t('Buying Price')}}</div>
          <div class="cell-item-rows-value" style="color: rgb(2, 175, 116)">₹{{e.buy_price}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-rows-name cell-item-rows-name-padding">{{t('Closing Price')}}</div>
          <div class="cell-item-rows-value" style="color: rgb(2, 175, 116)">{{e.closing_price}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-rows-name">{{t('Number of Shares Held')}}</div>
          <div class="cell-item-rows-value" style="color: rgb(2, 175, 116)">{{decimalpre(e.quantity)}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-rows-name cell-item-rows-name-padding">
            {{t('Position Amount')}}
          </div>
          <div class="cell-item-rows-value" style="color: rgb(2, 175, 116)">₹{{decimalpre(e.postionAmount)}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-rows-name">{{t('Profit')}}</div>
          <div class="cell-item-rows-value" :class="`${e.profit >= 0 ? 'upper' : 'lower'}`">₹{{decimalpre(e.profit)}}</div>
        </div>
        <div class="cell-item">
          <div class="cell-item-rows-name cell-item-rows-name-padding">{{t('Direction')}}</div>
          <div class="cell-item-rows-value" :class="`${e.profit >= 0 ? 'upper' : 'lower'}`">{{e.direc}}</div>
        </div>
      </div>
    </template>
    <div  class="empty" style="width: 80%;margin: 20px auto;" v-if="!orderList.length">
      <img
        style="width: 100%"
        src="@/assets/images/No-records_03.df9abc64.png"
        alt=""
      />
    </div>
  </div>

  <van-dialog v-model:show="show"  show-cancel-button :beforeClose="sellHandler">
    <div  class="dialog-container">
      <div  class="dialog-container-title">{{t('Confirm Sell?')}}</div>
      <div  class="dialog-container-cell">
        <div  class="dialog-container-cell-item">
          <div  class="dialog-container-cell-item-name">{{curStock.name}}</div>
        </div>
        <div  class="dialog-container-cell-item">
          <div  class="dialog-container-cell-item-name">{{t('Buying Price')}}</div>
          <div  class="dialog-container-cell-item-value">₹{{curStock.buy_price}}</div>
        </div>
        <div  class="dialog-container-cell-item">
          <div  class="dialog-container-cell-item-name">{{t('Current Price')}}</div>
          <div  class="dialog-container-cell-item-value">₹{{curStock.close}}</div>
        </div>
        <div  class="dialog-container-cell-item">
          <div  class="dialog-container-cell-item-name">{{t('Number of Shares Held')}}</div>
          <div  class="dialog-container-cell-item-value">{{decimalpre(curStock.quantity)}}</div>
        </div>
        <div  class="dialog-container-cell-item">
          <div  class="dialog-container-cell-item-name">{{t('Position Amount')}}</div>
          <div  class="dialog-container-cell-item-value">₹{{decimalpre(curStock.postionAmount)}}</div>
        </div>
        <div  class="dialog-container-cell-item">
          <div  class="dialog-container-cell-item-name">{{t('Profit')}}</div>
          <div  class="dialog-container-cell-item-value">₹{{decimalpre(curStock.profit)}}</div>
        </div>
        <div  class="dialog-container-cell-item">
          <div  class="dialog-container-cell-item-name">{{t('Service Fee')}}</div>
          <div  class="dialog-container-cell-item-value">₹{{decimalpre(curStock.fee)}}</div>
        </div>
        <div  class="dialog-container-cell-item">
          <div  class="dialog-container-cell-item-name">{{t('Direction')}}</div>
          <div class="dialog-container-cell-item-value" :class="`${curStock.profit >= 0 ? 'upper' : 'lower'}`">{{curStock.direc}}</div>
        </div>
      </div>
    </div>
  </van-dialog>
  </div>

</template>
<script setup>
import { useRouter,  } from "vue-router";
import { ref, computed } from "vue";
import { post } from '@/utils/request'
import { showLoadingToast, closeToast,showToast } from 'vant'
import { date,decimalpre } from '@/utils/util'
import store, { checkExchangeTimeRage } from '@/store/index'
import { t } from '@/languages'
const uType = ref();
const show = ref(false);
const orderList = ref([])
const exchangeMap = computed(() => store.exchangeMap)
const curStock = ref({})


function checkUType(type) {
  if (uType.value == type) return;
  uType.value = type;
  getStocksList()
}
const $router = useRouter();
function handleFunc(path) {
  $router.push({ path });
}

function sell(e){
  const isInTime = checkExchangeTimeRage()
  if(!isInTime) {
    showToast(t('Non trading hours'))
    return
  }
  curStock.value = e
  show.value = true
}
function go(e){
  $router.push({
    path: "/marketDetails",
    query: {
      name: e.name,
      ticker: e.ticker,
      excode: e.excode
    }
  });
}

async function getStocksList() {
  try {
    showLoadingToast()
    const res = await post('/api/app/stocks/', {
      type: uType.value
    })
    const list = res || []
    orderList.value = list.map(e => {
      const realtime = exchangeMap.value[e.ticker] || {}
      const postionAmount = realtime.close * e.quantity
      let profit = postionAmount - e.buy_price * e.quantity
      profit = profit ? profit.toFixed(2) : 0
      const fee = uType.value === 'closing' ? postionAmount * 0.002 : e.buy_price * e.quantity * 0.002
      return {
        ...e,
        ...realtime,
        fee: fee.toFixed(2),
        postionAmount: postionAmount ? postionAmount.toFixed(2) : '',
        profit,
        direc: profit > 0? 'Up' : profit === 0 ? '' : 'down'
      }
    })
  } catch (error) {
    console.log(error)
    orderList.value = []
  } finally {
    closeToast()
  }
}

function sellHandler(e) {
  
  if(e === 'confirm') {
    showLoadingToast()
      return new Promise(async (resolve, reject) => {
        try {
          const res = await post('/api/app/stock/out/', {
            ticker: curStock.value.ticker,
            current_price: curStock.value.close,
            order_id: curStock.value.id
          })
          showToast(t('Successfull'))
          getStocksList()
          resolve(true)
        } catch (error) {
          console.log(error)
          resolve(true)
        }
      })
    
  }
  return true
}

checkUType('normal')
</script>

<style lang="scss" >
.van-dialog {
  background: #0d111a;
}

.van-button--default {
  background: #98aee0;
}
 .van-dialog {
    background: #0d111a
}

 .van-button--default {
    background: #98aee0
}

.position {
    color: #fff
}

.position .container {
    padding: .4rem .26667rem;
    padding-bottom: 2.13333rem
}

.position .container .title_color {
    font-size: .48rem;
    font-weight: 600;
    margin-left: .26667rem;
    margin-bottom: .4rem
}

.position .container .label {
    margin: 0 1.06667rem;
    display: flex;
    justify-content: space-around;
    background: url("@/assets/images/Holding_03.936501e4.png");
    background-size: 100% 100%;
    height: 1.33333rem;
    color: #fff;
    line-height: 1.06667rem;
    font-weight: 700;
    font-size: .4rem
}

.position .container .active {
    color: #62f8a2
}

.position .isRecord {
    font-size: .37333rem;
    text-align: center;
    padding: .26667rem 0
}

.position .cell {
    margin-top: .53333rem;
    box-shadow: 0 .10667rem .37333rem 0 rgba(0,0,0,.15);
    border-radius: .32rem;
    border: .02667rem solid #2b4e5a
}

.position .cell .cell-item-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: .26667rem .53333rem;
    background: #0f3a40;
    border-top-left-radius: .26667rem;
    border-top-right-radius: .26667rem
}

.position .cell .cell-item-head .cell-item-head-title {
    font-size: .37333rem;
    flex: 5;
    flex-shrink: 0;
    white-space: pre-wrap
}

.position .cell .cell-item-head .cell-item-head-title-small {
    margin-top: .08rem;
    font-size: .29333rem;
    color: #999
}

.position .cell .cell-item-head .cell-item-head-value {
    flex-shrink: 0;
    width: 1.2rem;
    background: linear-gradient(270deg,#d02f5e,#fed053);
    border-radius: .32rem;
    text-align: center;
    color: #0e1822;
    font-size: .32rem;
    padding: .08rem .26667rem
}

.position .cell .cell-item {
    padding: .13333rem .26667rem;
    // border-bottom: .02667rem solid #0a272b;
    display: flex;
    justify-content: space-between;
    background: #0e1822;
    border: none !important;
}

.position .cell .cell-item .cell-item-name,.position .cell .cell-item .cell-item-value {
    font-size: .32rem
}

.position .cell .cell-item .cell-item-row {
    display: flex;
    justify-content: space-between
}

.position .cell .cell-item:last-child {
    border-bottom-left-radius: .26667rem;
    border-bottom-right-radius: .26667rem
}

.position .cell .cell-item-rows {
    display: flex
}

.position .cell .cell-item-rows .cell-item-row {
    display: flex;
    flex: 1;
    height: .66667rem;
    font-size: .37333rem
}

.position .cell .cell-item-rows .cell-item-row .cell-item-rows-name {
    font-size: .32rem
}

.position .cell .cell-item-rows .cell-item-row .cell-item-rows-name-padding {
    padding-left: .26667rem
}

.position .cell .cell-item-rows .cell-item-row .cell-item-rows-value {
    flex: 1;
    text-align: right;
    font-size: .32rem
}

.position .more {
    font-size: .37333rem;
    text-align: center;
    padding: .26667rem 0
}

.position .dialog-container {
    padding: .26667rem
}

.position .dialog-container .dialog-container-title {
    text-align: center;
    padding: .26667rem 0;
    color: #d73d3d
}

.position .dialog-container .dialog-container-cell .dialog-container-cell-item {
    display: flex;
    align-items: center;
    font-size: .37333rem;
    padding: .26667rem 0
}

.position .dialog-container .dialog-container-cell .dialog-container-cell-item .dialog-container-cell-item-value {
    flex: 1;
    text-align: right
}
.position .van-dialog{
  background-color: #0d111a !important;
}



</style>
